package com.security.securityandoauth.handler;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/*
 * 这个类似于JWT令牌拦截器，访问需要认证的资源而没认证时，会调用这个类，告知需先认证（跳转到登陆页面）
 */

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 封装数据
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("code", 403);
        resultMap.put("message", "请先登录");
        String result = JSON.toJSONString(resultMap);

        // 输出响应结果
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(result);
    }
}
